package com.lonely.my.rmi.provider;

import com.lonely.my.rmi.service.impl.UserInterfaceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;

import java.nio.charset.StandardCharsets;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.util.concurrent.CountDownLatch;

/**
 * @date: 2022-03-23 16:55
 * @author: ztkj-hzb
 * @description: 提供服务
 **/
@Slf4j
public class ProviderServer {


    public static void main(String[] args) throws Exception {

        //1.注册端口
        LocateRegistry.createRegistry(10000);

        //2. 发布服务
        String interfaceUrl = "rmi://localhost:10000/userInterface";
        Naming.bind(interfaceUrl, new UserInterfaceImpl());
        log.info("服务发布成功");

        //3. 注册到注册中心
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("101.132.184.56:12181", 3000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                log.info("连接成功");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();

        String interfaceNodePath = "/myRmi/userInterface";
        if(zooKeeper.exists(interfaceNodePath,false) != null){
            //已存在
            log.info("已存在节点，删除中");
            zooKeeper.delete(interfaceNodePath,0);
        }
        zooKeeper.create(interfaceNodePath, interfaceUrl.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        log.info("创建服务节点成功");
    }

}
